<template>
  <div class="asset-list">
    <!-- 搜索和操作栏 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" inline>
        <el-form-item label="资产名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入资产名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="资产分类">
          <el-select
            v-model="searchForm.category"
            placeholder="请选择分类"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="category in categories"
              :key="category.value"
              :label="category.label"
              :value="category.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="正常" value="正常" />
            <el-option label="维护中" value="维护中" />
            <el-option label="报废" value="报废" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加资产
      </el-button>
      <el-button type="success" @click="handleExport">
        <el-icon><Download /></el-icon>
        导出数据
      </el-button>
    </div>

    <!-- 资产列表 -->
    <el-card class="list-card" shadow="hover">
      <el-table
        :data="assetList"
        stripe
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="资产名称" min-width="200" />
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column prop="value" label="价值" width="120">
          <template #default="scope">
            ¥{{ scope.row.value.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="locationName" label="位置" width="150" />
        <el-table-column prop="purchaseDate" label="购买日期" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleView(scope.row)">
              查看
            </el-button>
            <el-button link type="warning" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资产名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入资产名称" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入资产编码" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资产分类" prop="category">
              <el-select v-model="form.category" placeholder="请选择分类" style="width: 100%">
                <el-option
                  v-for="category in categories"
                  :key="category.value"
                  :label="category.label"
                  :value="category.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="正常" value="正常" />
                <el-option label="维护中" value="维护中" />
                <el-option label="报废" value="报废" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资产价值" prop="value">
              <el-input-number
                v-model="form.value"
                :min="0"
                :precision="2"
                style="width: 100%"
                placeholder="请输入资产价值"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="位置" prop="location">
              <el-input v-model="form.location" placeholder="请输入资产位置" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="购买日期" prop="purchaseDate">
              <el-date-picker
                v-model="form.purchaseDate"
                type="date"
                placeholder="请选择购买日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplier">
              <el-input v-model="form.supplier" placeholder="请输入供应商" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="资产描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入资产描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 资产详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="资产详情"
      width="800px"
    >
      <div v-if="selectedAsset" class="asset-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="资产ID">{{ selectedAsset.id }}</el-descriptions-item>
          <el-descriptions-item label="资产名称">{{ selectedAsset.name }}</el-descriptions-item>
          <el-descriptions-item label="资产编码">{{ selectedAsset.code }}</el-descriptions-item>
          <el-descriptions-item label="资产分类">{{ selectedAsset.category }}</el-descriptions-item>
          <el-descriptions-item label="资产状态">
            <el-tag :type="getStatusType(selectedAsset.status)">
              {{ selectedAsset.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="资产价值">¥{{ selectedAsset.value?.toLocaleString() }}</el-descriptions-item>
          <el-descriptions-item label="位置">{{ selectedAsset.location }}</el-descriptions-item>
          <el-descriptions-item label="购买日期">{{ selectedAsset.purchaseDate }}</el-descriptions-item>
          <el-descriptions-item label="供应商">{{ selectedAsset.supplier }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ selectedAsset.createTime }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-description">
          <h4>资产描述</h4>
          <p>{{ selectedAsset.description || '暂无描述' }}</p>
        </div>
        
        <div class="detail-remark">
          <h4>备注信息</h4>
          <p>{{ selectedAsset.remark || '暂无备注' }}</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleEditFromDetail">编辑</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Download } from '@element-plus/icons-vue'
import { assetApi, categoryApi } from '@/api'
import { AssetStatusTextToCode, AssetStatusCodeToText } from '@/utils/status'

const router = useRouter()
const route = useRoute()

// 分类下拉以及名称映射
const categories = ref<any[]>([])
const loadCategories = async () => {
  const list: any = await categoryApi.getAll()
  categories.value = (list || []).map((c: any) => ({ label: c.name, value: c.id }))
}

// 根据分类 ID 获取名称
const getCategoryName = (id: number | null | undefined) => {
  if (!id) return ''
  const found = categories.value.find((c: any) => c.value === id)
  return found ? found.label : ''
}

// 搜索表单
const searchForm = reactive({
  name: '',
  category: '',
  status: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 资产列表数据
const assetList = ref<any[]>([])

// 加载状态
const loading = ref(false)
const submitting = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogTitle = ref('添加资产')
const formRef = ref()
const selectedAsset = ref<any>(null)

// 表单数据
const form = reactive({
  id: null,
  name: '',
  code: '',
  category: '',
  status: '正常',
  value: 0,
  location: '',
  purchaseDate: '',
  supplier: '',
  description: '',
  remark: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入资产名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入资产编码', trigger: 'blur' },
    { pattern: /^[A-Z0-9_-]+$/, message: '编码只能包含大写字母、数字、下划线和横线', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择资产分类', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  value: [
    { required: true, message: '请输入资产价值', trigger: 'blur' },
    { type: 'number', min: 0, message: '价值必须大于等于0', trigger: 'blur' }
  ],
  purchaseDate: [
    { required: true, message: '请选择购买日期', trigger: 'change' }
  ]
}

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case '正常':
      return 'success'
    case '维护中':
      return 'warning'
    case '报废':
      return 'danger'
    default:
      return 'info'
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    name: '',
    category: '',
    status: ''
  })
  handleSearch()
}

// 添加资产
const handleAdd = () => {
  dialogTitle.value = '添加资产'
  dialogVisible.value = true
}

// 查看资产
const handleView = (row: any) => {
  // 默认使用弹框式查看
  selectedAsset.value = row
  detailDialogVisible.value = true
}

// 编辑资产
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑资产'
  Object.assign(form, {
    ...row,
    category: row.categoryId
  })
  dialogVisible.value = true
}

// 从详情对话框编辑
const handleEditFromDetail = () => {
  if (selectedAsset.value) {
    dialogTitle.value = '编辑资产'
    Object.assign(form, {
      ...selectedAsset.value,
      category: selectedAsset.value.categoryId
    })
    detailDialogVisible.value = false
    dialogVisible.value = true
  }
}

// 删除资产
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除资产"${row.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await assetApi.delete(row.id)
      ElMessage.success('删除成功')
      // 刷新数据，重新获取第一页
      pagination.current = 1
      await loadData()
    } catch (e: any) {
      ElMessage.error(e?.message || '删除失败')
    }
  }).catch(() => {/* 用户取消 */})
}

// 导出数据
const handleExport = () => {
  ElMessage.success('导出功能开发中...')
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    const payload: any = {
      ...form,
      code: form.code,
      categoryId: form.category,
      status: AssetStatusTextToCode[form.status]
    }

    if (form.id) {
      await assetApi.update(form.id, payload)
      ElMessage.success('编辑成功')
    } else {
      await assetApi.add(payload)
      ElMessage.success('添加成功')
    }

    dialogVisible.value = false
    loadData()
  } catch (error: any) {
    // 已有响应拦截统一处理
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    id: null,
    name: '',
    code: '',
    category: '',
    status: '正常',
    value: 0,
    location: '',
    purchaseDate: '',
    supplier: '',
    description: '',
    remark: ''
  })
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.size = size
  loadData()
}

// 当前页改变
const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadData()
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params: any = {
      current: pagination.current,
      size: pagination.size,
      name: searchForm.name,
      categoryId: searchForm.category,
      status: searchForm.status ? AssetStatusTextToCode[searchForm.status] : undefined
    }
    const res: any = await assetApi.getList(params)
    const rows = res.list || res.records || []
    assetList.value = rows.map((r: any) => ({
      ...r,
      categoryName: getCategoryName(r.categoryId),
      locationName: r.location || '',
      createTime: r.createdAt || r.createTime || '',
      status: AssetStatusCodeToText[r.status] || '未知'
    }))
    pagination.total = res.total || rows.length || 0
  } finally {
    loading.value = false
  }
}

// 监听路由参数，处理直接访问编辑页面的情况
watch(() => route.params, (params) => {
  if (params.id) {
    if (route.name === 'AssetEdit') {
      const assetId = parseInt(params.id as string)
      const asset = assetList.value.find(item => item.id === assetId)
      if (asset) {
        handleEdit(asset)
      } else {
        ElMessage.error('资产不存在')
        router.push('/asset/list')
      }
    } else if (route.name === 'AssetDetail') {
      const assetId = parseInt(params.id as string)
      const asset = assetList.value.find(item => item.id === assetId)
      if (asset) {
        handleView(asset)
      } else {
        ElMessage.error('资产不存在')
        router.push('/asset/list')
      }
    }
  }
}, { immediate: true })

onMounted(() => {
  loadCategories()
  loadData()
})
</script>

<style scoped>
.asset-list {
  padding: 0;
}

.search-card {
  margin-bottom: 20px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.list-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.asset-detail {
  padding: 20px 0;
}

.detail-description,
.detail-remark {
  margin-top: 20px;
}

.detail-description h4,
.detail-remark h4 {
  color: #303133;
  margin-bottom: 10px;
}

.detail-description p,
.detail-remark p {
  color: #606266;
  line-height: 1.6;
  margin: 0;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style> 